package com.zmcc.clients;

import com.google.gson.Gson;
import com.zmcc.entity.VerifResult;
import com.zmcc.entity.VerifTemplate;
import com.zmcc.entity.common.CommonRequest;
import com.zmcc.entity.common.CommonResponse;
import com.zmcc.sender.DefaultSyncClient;
import com.zmcc.sender.ISyncClient;
import com.zmcc.service.IVerifRequest;
import com.zmcc.service.impl.VerifRequestCommercial;
import com.zmcc.utils.WrapperUtils;

public class VerifClient {

    private final IVerifRequest requestWrapper;

    private final ISyncClient syncClient;

    private final String appkey;

    private final String appsecret;

    private final String mode;

    public VerifClient(VerifClient.Builder builder) {
        this.appkey = builder.appkey;
        this.appsecret = builder.appsecret;
        this.mode = builder.mode;
        this.syncClient = DefaultSyncClient.getInstance();
        this.requestWrapper = VerifRequestCommercial.getInstance();
    }

    public static class Builder {
        private String appkey;
        private String appsecret;
        private String mode;

        public Builder() {

        }

        public VerifClient.Builder appkey(String appkey) {
            this.appkey = appkey;
            return this;
        }

        public VerifClient.Builder appsecret(String appsecret) {
            this.appsecret = appsecret;
            return this;
        }

        public VerifClient.Builder mode(String mode) {
            this.mode = mode;
            return this;
        }

        public VerifClient build() {
            return new VerifClient(this);
        }
    }

    public VerifResult bind(VerifTemplate template) {
        CommonRequest request = this.requestWrapper.getVerifBindSendRequest(template);
        request.setHeaderParams(WrapperUtils.authHeaderToMap(WrapperUtils.authHeader(appkey, appsecret)));
        CommonResponse response =  this.syncClient.fetch(request);
        return new Gson().fromJson(response.getData(), VerifResult.class);
    }

    public VerifResult unbind(String requestid,String subscriptionid,String dn,String checkdn) {
        CommonRequest request = this.requestWrapper.getVerifUnBindSendRequest(requestid, subscriptionid, dn, checkdn);
        request.setHeaderParams(WrapperUtils.authHeaderToMap(WrapperUtils.authHeader(appkey, appsecret)));
        CommonResponse response =  this.syncClient.fetch(request);
        return new Gson().fromJson(response.getData(), VerifResult.class);
    }

    public VerifResult queryStatus(String requestid,String servicecode,String dn,String checkNumber) {
        CommonRequest request = this.requestWrapper.getVerifQueryStatusRequest(requestid, servicecode, dn, checkNumber);
        request.setHeaderParams(WrapperUtils.authHeaderToMap(WrapperUtils.authHeader(appkey, appsecret)));
        CommonResponse response =  this.syncClient.fetch(request);
        return new Gson().fromJson(response.getData(), VerifResult.class);
    }
}
